#!/bin/bash

# 服务器端RocketMQ应用管理脚本

APP_NAME="rocketmq-app"
CONTAINER_NAME="rocketmq-app"
LOG_DIR="/home/rocketmq/logs/app"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 显示帮助信息
show_help() {
    echo "RocketMQ应用管理脚本"
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  start     启动应用"
    echo "  stop      停止应用"
    echo "  restart   重启应用"
    echo "  status    查看应用状态"
    echo "  logs      查看应用日志"
    echo "  health    健康检查"
    echo "  update    更新应用"
    echo "  help      显示此帮助信息"
    echo ""
}

# 启动应用
start_app() {
    print_message $BLUE "正在启动RocketMQ应用..."
    
    # 检查容器是否已存在
    if docker ps -a --format "table {{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
        print_message $YELLOW "容器已存在，正在启动..."
        docker start $CONTAINER_NAME
    else
        print_message $YELLOW "容器不存在，正在创建并启动..."
        docker run -d \
            --name $CONTAINER_NAME \
            --network rmq \
            -p 8080:8080 \
            -e SPRING_PROFILES_ACTIVE=prod \
            -e ROCKETMQ_NAMESRV_ADDR=192.168.211.139:9876 \
            -v $LOG_DIR:/app/logs \
            --restart unless-stopped \
            rocketmq-app:latest
    fi
    
    if [ $? -eq 0 ]; then
        print_message $GREEN "应用启动成功！"
        sleep 5
        check_health
    else
        print_message $RED "应用启动失败！"
        exit 1
    fi
}

# 停止应用
stop_app() {
    print_message $BLUE "正在停止RocketMQ应用..."
    docker stop $CONTAINER_NAME
    
    if [ $? -eq 0 ]; then
        print_message $GREEN "应用停止成功！"
    else
        print_message $RED "应用停止失败！"
        exit 1
    fi
}

# 重启应用
restart_app() {
    print_message $BLUE "正在重启RocketMQ应用..."
    docker restart $CONTAINER_NAME
    
    if [ $? -eq 0 ]; then
        print_message $GREEN "应用重启成功！"
        sleep 5
        check_health
    else
        print_message $RED "应用重启失败！"
        exit 1
    fi
}

# 查看应用状态
check_status() {
    print_message $BLUE "应用状态:"
    echo "=================================="
    
    # 检查容器状态
    if docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep -q "^${CONTAINER_NAME}"; then
        print_message $GREEN "✓ 容器正在运行"
        docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep $CONTAINER_NAME
    else
        print_message $RED "✗ 容器未运行"
        # 检查是否有停止的容器
        if docker ps -a --format "table {{.Names}}\t{{.Status}}" | grep -q "^${CONTAINER_NAME}"; then
            print_message $YELLOW "容器已停止:"
            docker ps -a --format "table {{.Names}}\t{{.Status}}" | grep $CONTAINER_NAME
        fi
    fi
    
    echo ""
    
    # 检查端口占用
    if netstat -tlnp 2>/dev/null | grep -q ":8080 "; then
        print_message $GREEN "✓ 端口8080正在监听"
        netstat -tlnp | grep ":8080 "
    else
        print_message $RED "✗ 端口8080未监听"
    fi
    
    echo ""
    
    # 检查网络连接
    if docker network ls | grep -q rmq; then
        print_message $GREEN "✓ 网络rmq存在"
    else
        print_message $RED "✗ 网络rmq不存在"
    fi
}

# 查看应用日志
show_logs() {
    print_message $BLUE "应用日志 (最近50行):"
    echo "=================================="
    
    if docker ps --format "{{.Names}}" | grep -q "^${CONTAINER_NAME}$"; then
        docker logs --tail 50 $CONTAINER_NAME
    else
        print_message $RED "容器未运行，无法查看日志"
    fi
}

# 健康检查
check_health() {
    print_message $BLUE "执行健康检查..."
    echo "=================================="
    
    # 等待应用启动
    print_message $YELLOW "等待应用启动..."
    for i in {1..12}; do
        if curl -f http://localhost:8080/api/rocketmq/health >/dev/null 2>&1; then
            print_message $GREEN "✓ 应用健康检查通过！"
            echo "响应时间: $((i*5))秒"
            return 0
        fi
        echo -n "."
        sleep 5
    done
    
    print_message $RED "✗ 应用健康检查失败！"
    print_message $YELLOW "请检查应用日志: docker logs $CONTAINER_NAME"
    return 1
}

# 更新应用
update_app() {
    print_message $BLUE "正在更新应用..."
    
    # 检查是否有新的镜像文件
    if [ -f "rocketmq-rate-limit-demo-image.tar" ]; then
        print_message $YELLOW "发现新的镜像文件，正在更新..."
        
        # 停止应用
        stop_app
        
        # 加载新镜像
        print_message $BLUE "加载新镜像..."
        docker load -i rocketmq-rate-limit-demo-image.tar
        
        # 删除旧容器
        print_message $BLUE "删除旧容器..."
        docker rm $CONTAINER_NAME 2>/dev/null || true
        
        # 启动新应用
        start_app
        
        # 清理镜像文件
        print_message $BLUE "清理临时文件..."
        rm -f rocketmq-rate-limit-demo-image.tar
        
        print_message $GREEN "应用更新完成！"
    else
        print_message $YELLOW "未发现新的镜像文件"
        print_message $BLUE "请先上传新的镜像文件到服务器"
    fi
}

# 主函数
main() {
    case "$1" in
        start)
            start_app
            ;;
        stop)
            stop_app
            ;;
        restart)
            restart_app
            ;;
        status)
            check_status
            ;;
        logs)
            show_logs
            ;;
        health)
            check_health
            ;;
        update)
            update_app
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_message $RED "未知命令: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 检查参数
if [ $# -eq 0 ]; then
    show_help
    exit 1
fi

# 执行主函数
main "$@"

